package com.gzy.xuexiziliao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gzy.xuexiziliao.common.result.PageResult;
import com.gzy.xuexiziliao.mapper.StudentMapper;
import com.gzy.xuexiziliao.pojo.entity.Information;
import com.gzy.xuexiziliao.pojo.entity.Student;
import com.gzy.xuexiziliao.service.StudentService;
import com.gzy.xuexiziliao.utils.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService {
    private static final Logger log = LoggerFactory.getLogger(StudentServiceImpl.class);
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public void save(Student student) {
        student.setCreateTime(LocalDate.now());
        student.setUpdateTime(LocalDate.now());
        studentMapper.save(student);

    }

    @Override
    public void delete(List<Integer> ids) {
        studentMapper.delete(ids);
    }

    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDate.now());
        studentMapper.update(student);
    }

    @Override
    public Student getById(Integer id) {
        Student student = studentMapper.getById(id);
        return student;
    }

    /**
     * 通过openid查询学生信息
     * @param openid
     * @return
     */
    @Override
    public Student getByOpenId(String openid) {
        Student student = studentMapper.getByOpenId(openid);
        return student;
    }

    @Override
    public PageResult page(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end) {
        //1.设置分页参数
        PageHelper.startPage(page, pageSize);
        //2.执行查询
        List<Student> studentsList = studentMapper.list(name, gender, begin, end);
        Page<Student> p = (Page<Student>) studentsList;
        //3.封装对象
        PageResult pageResult = new PageResult(p.getTotal(), p.getResult());
        return pageResult;

    }


    @Override
    public List<Student> getByName(String name) {
        if (name != null) {
            List<Student> student = studentMapper.getByName(name);
            return student;
        }
        return null;
    }
    //微信接口地址
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public Student wxlogin(Student student) {
        //调用微信接口服务，获取openid
        Map<String, String> map = new HashMap<>();
        map.put("appid", "wx2b93861f67c39712");
        map.put("secret", "4f12fb300779ecab38f2a9fdde80e6f0");
        map.put("js_code", student.getCode());
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        //判断openid是否为空，如果为空，则提示登录失败
        if (openid == null) {
            throw new RuntimeException("登录失败");
        }
        //判断是否为新用户，如果是新用户，自动完成注册
        Student stu = studentMapper.getByOpenId(openid);
        if (stu == null) {
            stu = Student.builder()
                    .openid(openid)
                    .status(0)
                    .createTime(LocalDate.now())
                    .build();
            studentMapper.save(stu);
            studentMapper.addStudentId(stu.getStudentId());

        }
        log.info("stu的值为:{}", stu.getStudentId());

        //返回用户对象
        return stu;
    }

    @Override
    public void UpdateUserInfo(Student student) {

        student.setUpdateTime(LocalDate.now());
        student.setStatus(1);
        studentMapper.UpdateUserInfo(student);

        log.info("student:{}", student);
    }


    // 正确示例：直接返回查询结果
    @Override
    public int checkstatus(Student student) {
        Student statusByStudent = studentMapper.getStatusByStudentId(student);
        return statusByStudent.getStatus();
    }

    @Override
    public PageResult informationpage(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end) {
        // 1. 设置分页参数
        PageHelper.startPage(page, pageSize);

        // 2. 执行查询（添加状态参数 status=1）
        List<Information> informationList = studentMapper.informationlist(
                name,
                gender,
                begin,
                end,
                (short) 1 // 固定传入状态为1（已发布）
        );

        // 3. 封装分页结果
        Page<Information> p = (Page<Information>) informationList;
        PageResult pageResult = new PageResult(p.getTotal(), p.getResult());
        return pageResult;
    }

    @Override
    public String getPhone(Integer id) {
        String phone = studentMapper.getPhone(id);
        if (phone != null) {
            return phone;
        }
        return null;
    }
}



